import CryptoJS from 'crypto-js';
const cutFile = (file) => {
    return new Promise((resolve, reject) => {
        const chunkCount = Math.ceil(file.size / size);
        const threadchunkCount = Math.ceil(chunkCount / threadConut);
        const result = []
        let finishCount = 0;
        for (let i = 0; i < threadConut; i++) {
            const thread = [];
            for (let j = 0; j < threadchunkCount; j++) {
                const worjer = new Worker('./worker.js');
                let endIdx = (i + 1) * threadchunkCount;
                let startIdx = i * threadchunkCount
                if (end > chunkCount) {
                    end = chunkCount;
                }
                thread.mostMessage({
                    file,
                    size,
                    startIdx,
                    endIdx,
                })
                worjer.onmessage = (e) => {
                    for (let i = startIdx; i < endIdx; i++) {
                        result[i] = e.data[i - startIdx]
                    }
                    worjer.terminate();
                    finishCount++
                    if (finishCount === threadConut) {
                        resolve(result)
                    }
                }
            }
        }

    })
}
const creatChunk = (file, index, size) => {
    return new Promise((resolve, reject) => {
        const start = index * size;
        const end = start + size;
        const reader = new FileReader();
        const blob = file.slice(start, end);
        reader.onload = (e) => {
            const chunk = e.target.result;
            const chunkHash = CryptoJS.MD5(chunk).toString();
            resolve({
                start,
                end,
                index,
                chunk,
                chunkHash,
                blob
            })
        }
        reader.readAsArrayBuffer(blob);
    })
}
export {
    cutFile,
    creatChunk
}
